import { api } from './auth';

// 积分包接口
export interface CreditPackage {
  id: string;
  name: string;
  price: number;
  credits: number;
  features: string[];
  popular?: boolean;
  validDays: number;
}

// 用户积分信息接口
export interface UserCredits {
  userId: number;
  creditBalance: number;
  expiresAt?: string;
  daysUntilExpiration?: number;
  isExpired: boolean;
}

// 积分交易记录接口
export interface CreditTransaction {
  id: string;
  userId: number;
  transactionType: 'purchase' | 'usage' | 'refund' | 'expiration';
  creditAmount: number;
  description?: string;
  referenceId?: string;
  metadata?: Record<string, any>;
  createdAt: string;
}

// API响应接口
interface ApiResponse<T> {
  success: boolean;
  data: T;
  message: string;
}

// 积分服务
export const creditsService = {
  // 获取积分包列表
  getCreditPackages: async (): Promise<CreditPackage[]> => {
    // 临时解决方案：使用本地定义的积分包数据
    console.log('Using local credit packages definition');
    return CREDIT_PACKAGES;
    
    /* 暂时注释掉API调用，使用本地数据
    try {
      const response = await api.get<ApiResponse<CreditPackage[]>>('/credits/packages');
      return response.data.data;
    } catch (error: any) {
      console.error('获取积分包列表失败:', error);
      throw new Error(error.response?.data?.message || '获取积分包列表失败');
    }
    */
  },

  // 获取用户积分信息
  getUserCredits: async (userId: number): Promise<UserCredits> => {
    try {
      const response = await api.get<ApiResponse<UserCredits>>(`/credits/users/${userId}`);
      return response.data.data;
    } catch (error: any) {
      console.error('获取用户积分信息失败:', error);
      throw new Error(error.response?.data?.message || '获取用户积分信息失败');
    }
  },

  // 使用积分
  useCredits: async (params: {
    userId: number;
    credits: number;
    description?: string;
    referenceId?: string;
    metadata?: Record<string, any>;
  }): Promise<UserCredits> => {
    try {
      const response = await api.post<ApiResponse<UserCredits>>(
        `/credits/users/${params.userId}/use`,
        {
          credits: params.credits,
          description: params.description,
          referenceId: params.referenceId,
          metadata: params.metadata,
        }
      );
      return response.data.data;
    } catch (error: any) {
      console.error('使用积分失败:', error);
      throw new Error(error.response?.data?.message || '使用积分失败');
    }
  },

  // 获取用户积分交易历史
  getUserTransactions: async (
    userId: number,
    limit: number = 20,
    offset: number = 0
  ): Promise<CreditTransaction[]> => {
    try {
      const response = await api.get<ApiResponse<CreditTransaction[]>>(
        `/credits/users/${userId}/transactions?limit=${limit}&offset=${offset}`
      );
      return response.data.data;
    } catch (error: any) {
      console.error('获取积分交易历史失败:', error);
      throw new Error(error.response?.data?.message || '获取积分交易历史失败');
    }
  },

  // 处理支付成功后的积分添加
  handlePaymentSuccess: async (
    userId: number,
    packageId: string,
    paymentIntentId: string
  ): Promise<UserCredits> => {
    try {
      const response = await api.post<ApiResponse<UserCredits>>('/credits/payment-success', {
        userId,
        packageId,
        paymentIntentId,
      });
      return response.data.data;
    } catch (error: any) {
      console.error('处理支付成功失败:', error);
      throw new Error(error.response?.data?.message || '处理支付成功失败');
    }
  },

  // 检查积分是否足够
  checkCreditsAvailable: async (userId: number, requiredCredits: number): Promise<boolean> => {
    try {
      const userCredits = await creditsService.getUserCredits(userId);
      return userCredits.creditBalance >= requiredCredits && !userCredits.isExpired;
    } catch (error) {
      console.error('检查积分可用性失败:', error);
      return false;
    }
  },

  // 格式化过期信息
  formatExpirationInfo: (userCredits: UserCredits): {
    message: string;
    type: 'error' | 'warning' | 'info' | null;
  } => {
    if (userCredits.isExpired) {
      return {
        message: '⚠️ Your credits have expired',
        type: 'error'
      };
    }

    if (userCredits.daysUntilExpiration !== undefined) {
      if (userCredits.daysUntilExpiration === 0) {
        return {
          message: '⚠️ Your credits expire today',
          type: 'error'
        };
      }
      
      if (userCredits.daysUntilExpiration <= 7) {
        return {
          message: `⚠️ Your credits will expire in ${userCredits.daysUntilExpiration} days`,
          type: 'warning'
        };
      }
      
      return {
        message: `Your credits will expire in ${userCredits.daysUntilExpiration} days`,
        type: 'info'
      };
    }

    return {
      message: '',
      type: null
    };
  },

  // 格式化交易金额显示
  formatTransactionAmount: (transaction: CreditTransaction): string => {
    const sign = transaction.creditAmount > 0 ? '+' : '';
    return `${sign}${transaction.creditAmount}`;
  },

  // 获取交易类型的显示文本
  getTransactionTypeText: (type: CreditTransaction['transactionType']): string => {
    const typeMap = {
      'purchase': 'Purchase',
      'usage': 'Usage',
      'refund': 'Refund',
      'expiration': 'Expiration'
    };
    return typeMap[type] || type;
  },

  // 获取交易类型的颜色
  getTransactionTypeColor: (type: CreditTransaction['transactionType']): string => {
    const colorMap = {
      'purchase': 'text-green-600',
      'usage': 'text-blue-600',
      'refund': 'text-yellow-600',
      'expiration': 'text-red-600'
    };
    return colorMap[type] || 'text-gray-600';
  }
};

// 为了向后兼容，导出一些预定义的积分包（从API获取前的fallback）
export const CREDIT_PACKAGES: CreditPackage[] = [
  {
    id: 'basic',
    name: 'Basic',
    price: 9.99,
    credits: 30,
    validDays: 30,
    features: [
      '30 room redesigns',
      'Standard resolution images',
      '5 design styles',
      'Valid for 30 days'
    ]
  },
  {
    id: 'pro',
    name: 'Pro',
    price: 19.99,
    credits: 100,
    validDays: 60,
    popular: true,
    features: [
      '100 room redesigns',
      'High resolution images',
      'All design styles',
      'Download options',
      'Valid for 60 days'
    ]
  },
  {
    id: 'premium',
    name: 'Premium',
    price: 49.99,
    credits: 300,
    validDays: 90,
    features: [
      '300 room redesigns',
      'Ultra-high resolution images',
      'All design styles',
      'Priority processing',
      'Download options',
      'Valid for 90 days'
    ]
  }
];

export default creditsService; 